//
//  Application+Extension.swift
//  EastNetWorkProject
//
//  Created by 伊伊 on 2023/12/28.
//

import Foundation
import UIKit
struct Application{
   static var appVersion:String{
        let infoDictionary = Bundle.main.infoDictionary
        let version = infoDictionary?["CFBundleShortVersionString"]
        return version as! String
    }
    
    static var appBuildVersion:String{
        let infoDictionary = Bundle.main.infoDictionary
        let appBuildVersion = infoDictionary?["CFBundleVersion"]
        return appBuildVersion as! String
    }
  static func getAnonymous_id() -> String{
        let anonymous_id  = NSUUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased()
        return anonymous_id
    }

    static var cachesPath:String{
       return NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
    }
    
    static var libraryPath:String{
       return NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first!
    }
    
    static var documentsPath:String{
        return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
    }
    
    static  func visibleWindow() -> UIWindow?{
        let scene =  UIApplication.shared.connectedScenes.first
        guard  let windowscene = scene as? UIWindowScene else{
            let window =  UIApplication.shared.delegate?.window ?? nil
            return window
            
        }
        
        guard let delegate = windowscene.delegate as? SceneDelegate else{
            let window =  UIApplication.shared.delegate?.window ?? nil
            return window
        }
        
        return delegate.window
    }

   static var visibleViewController:UIViewController?{
        guard let rootController =  Application.visibleWindow()?.rootViewController else { return nil }
        let visiblevc =  self.visibleViewControllerIfExist(rootController)
        return visiblevc
    }
   
    private static func visibleViewControllerIfExist(_ vc:UIViewController) -> UIViewController?{
        if(vc.presentedViewController != nil){
            return self.visibleViewControllerIfExist(vc)
        }
        if(vc.isKind(of: UINavigationController.self)){
            let nabarvc = vc as! UINavigationController
            guard let vc = nabarvc.topViewController else { return nil }
            return self.visibleViewControllerIfExist(vc)
        }
        
        if(vc.isKind(of: UITabBarController.self)){
            let tabarvc = vc as! UITabBarController
            guard let seletedVc = tabarvc.selectedViewController else { return nil }
            return self.visibleViewControllerIfExist(seletedVc)
        }
        
        if(vc.isViewLoaded == true && vc.view.isHidden == false && vc.view.alpha > 0.01){
            return vc;
        }else{
            return nil
        }
    }

}
